package com.microloong.rfid.Service;

import com.microloong.rfid.model.Const;
import com.microloong.rfid.util.FRORfid;
import com.microloong.rfid.util.StreamUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.Socket;
import java.util.HashMap;

/**
 * @author MicroLOONG
 */
@Service
public class ConnectService {

    private final Log log = LogFactory.getLog(ConnectService.class);

    public void connectTask() throws Exception {
        RestTemplate restTemplate = new RestTemplate();
        // 连接
        Socket rfidSocket = StreamUtil.getSocket(Const.RFID_IP, Const.RFID_PORT);
        Socket rgbSocket = StreamUtil.getSocket(Const.RGB_IP, Const.RGB_PORT);
        // 循环读取数据
        while (true) {
            // 如果全部连接成功
            if (rfidSocket != null && rgbSocket != null) {
                // 寻卡
                StreamUtil.writeCommand(rfidSocket.getOutputStream(), Const.RFID_FIND);
                Thread.sleep(Const.time / 2);
                byte[] readBuff = StreamUtil.readData(rfidSocket.getInputStream());
                if (FRORfid.isFound(readBuff)) {
                    // 寻卡成功后才读卡号
                    StreamUtil.writeCommand(rfidSocket.getOutputStream(), Const.RFID_READ);
                    Thread.sleep(Const.time / 2);
                    readBuff = StreamUtil.readData(rfidSocket.getInputStream());
                    String cardId = FRORfid.getCardId(readBuff);
                    if (cardId != null) {
                        Const.CARD_ID = cardId;
                        if (!"0002020A".equals(cardId) && !"00000000".equals(cardId)) {
                            HashMap<String, String> map = new HashMap<>(4);
                            map.put("card", cardId);
                            ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://127.0.0.1:8888/check?card={card}", String.class, map);
                            log.info("Card ID: " + cardId);
                            log.info("Response: " + responseEntity.getBody());
                            StreamUtil.writeCommand(rgbSocket.getOutputStream(), Const.GREEN_CMD);
                        } else {
                            log.info("Card Read Error");
                            StreamUtil.writeCommand(rgbSocket.getOutputStream(), Const.RED_CMD);
                        }
                        Thread.sleep(Const.time / 2);
                        StreamUtil.writeCommand(rgbSocket.getOutputStream(), Const.OFF_CMD);
                    }
                }
            }
            Thread.sleep(Const.time);
        }
    }

}
